import { defineStore } from 'pinia'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userInfo: null
  }),
  
  actions: {
    async login(username, password) {
      try {
        const response = await axios.post('/auth/login', {
          username,
          password
        })
        
        const { token } = response
        this.token = token
        localStorage.setItem('token', token)
        
        ElMessage({
          message: '登录成功',
          type: 'success'
        })
        
        // 移除这里的路由跳转，因为已经在 Login.vue 中处理了
        // router.push('/')
      } catch (error) {
        ElMessage({
          message: error.response?.data?.message || '登录失败',
          type: 'error'
        })
        throw error  // 抛出错误以便 Login.vue 可以捕获
      }
    },

    logout() {
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('token')
      router.push('/login')
    }
  },

  getters: {
    isLoggedIn: (state) => !!state.token
  }
}) 